package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.ProdPropConstant;
import com.powernode.domain.ProdProp;
import com.powernode.domain.ProdPropValue;
import com.powernode.mapper.ProdPropMapper;
import com.powernode.mapper.ProdPropValueMapper;
import com.powernode.service.ProdPropService;
import com.powernode.service.ProdPropValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = "com.powernode.service.impl.ProdPropServiceImpl")
public class ProdPropServiceImpl extends ServiceImpl<ProdPropMapper, ProdProp> implements ProdPropService{

    @Autowired
    private ProdPropMapper prodPropMapper;

    @Autowired
    private ProdPropValueMapper prodPropValueMapper;

    @Autowired
    private ProdPropValueService prodPropValueService;

    /**
     * ids1 --> ids2 -->filter设置即可
     * @param page
     * @param prodProp
     */
    @Override
    @Transactional
    public void selectProdPropPage(Page<ProdProp> page, ProdProp prodProp) {
        // 1. 分页查询，属性对象，属性对象中没有属性值
        prodPropMapper.selectPage(page, new LambdaQueryWrapper<ProdProp>()
            .like(StrUtil.isNotEmpty(prodProp.getPropName()), ProdProp::getPropName, prodProp.getPropName()));

        // 2. 调整记录
        List<ProdProp> records = page.getRecords();
        if (records == null || records.size() == 0) return;

        // 3. 获取所有属性所对应的属性值（获取全部的属性ids）
        List<Long> prodPropIds = records.stream().map(ProdProp::getPropId).collect(Collectors.toList());

        // 4. 根据所有的属性ids获取所有的属性值集合（属性值集合）
        List<ProdPropValue> prodPropValues = prodPropValueMapper
                .selectList(new LambdaQueryWrapper<ProdPropValue>()
                        .in(ProdPropValue::getPropId, prodPropIds));

        // 5. 循环过滤
        records.forEach(item -> {
            List<ProdPropValue> realValuesList = prodPropValues.stream()
                    .filter(record -> record.getPropId().equals(item.getPropId()))
                    .collect(Collectors.toList());

            item.setProdPropValues(realValuesList);
        });

    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @CacheEvict(key = ProdPropConstant.PROD_PROP_LIST)
    public boolean save(ProdProp entity) {
        // 1. 新增商品属性
        entity.setRule(2);
        entity.setShopId(1L);
        int isSuccess = prodPropMapper.insert(entity);

        if (isSuccess > 0) {
            // 2. 获取商品属性值集合对象
            List<ProdPropValue> prodPropValues = entity.getProdPropValues();

            // 3. 判断属性值是否有
            if (CollectionUtil.isEmpty(prodPropValues)) {
                throw new RuntimeException("服务器开小差了！");
            }


            Long propId  = entity.getPropId();
            // 4. 循环遍历
            prodPropValues.forEach(item -> {
                item.setPropId(propId);
            });

            // 5. 批量添加属性和属性值
            prodPropValueService.saveBatch(prodPropValues);

        }

        return isSuccess > 0;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @CacheEvict(key = ProdPropConstant.PROD_PROP_LIST)
    public boolean updateById(ProdProp entity) {
        // 1. 获取商品属性值集合
        List<ProdPropValue> prodPropValues = entity.getProdPropValues();
        if (CollectionUtil.isEmpty(prodPropValues)) {
            throw new RuntimeException("服务器开小差了！");
        }

        // 2. 商品属性集合不为空，删除原有的属性属性值集合
        prodPropValueMapper.delete(new LambdaQueryWrapper<ProdPropValue>().eq(ProdPropValue::getPropId, entity.getPropId()));

        // 3. 批量添加商品属性和属性值集合
        prodPropValueService.saveBatch(prodPropValues);
        return prodPropMapper.updateById(entity) > 0;
    }

    @Override
    @Transactional
    @CacheEvict(key = ProdPropConstant.PROD_PROP_LIST)
    public boolean removeById(Serializable id) {
        // 1. 先删除属性值
        prodPropValueMapper.delete(new LambdaQueryWrapper<ProdPropValue>().eq(ProdPropValue::getPropId, id));


        return prodPropMapper.deleteById(id) > 0;
    }

    @Override
    @Cacheable(key = ProdPropConstant.PROD_PROP_LIST)
    public List<ProdProp> list() {
        List<ProdProp> prodPropList = prodPropMapper.selectList(null);
        return prodPropList;
    }
}
